<?php

namespace apiend\modules\user\models;

use common\models\user\UserFollower;
use common\models\user\User;

class FollowForm extends BaseModel {
    /**
     * 关注人用户id
     * @var
     */
    public $followed_user_id;

    private $_follow_user_info;

    /**
     * 关注人用户别名
     * @var
     */
    public $remark;

    public function rules() {
        return [
            [['followed_user_id'], 'integer'],
            [['followed_user_id'], 'required'],
            [['followed_user_id'], 'validateFollowUser'],
            [['remark'], 'string', 'max' => '10', 'min' => '1'],
            [['remark','followed_user_id'],'required','on' => 'remark']
        ];
    }

    public function validateFollowUser($attribute) {
        if (!$this->hasErrors()) {
            $followUser = User::findOne($this->$attribute);
            if (!$followUser) {
                $this->addError($attribute, '关注用户不存在');
            }

            $this->_follow_user_info = $followUser;
        }
    }

    /**
     * 关注/取消关注
     * @param array $params
     * @return void
     */
    public function follow($params = []) {
        if(!$this->load($params,'')){
            parent::throwError('参数非法');
        }

        if (!$this->validate()) {
            parent::throwError('提交失败', $this->getFirstErrors());
        }

        $model = UserFollower::findOrNew(['followed_user_id' => $this->followed_user_id, 'user_id' => $this->_token->user_id]);

        if ($model->isNewRecord) {
            if (!$model->save()) {
                parent::throwError('关注失败', $model->getFirstErrors());
            }
            return $model;
        } else {
            if (!$model->delete()){
                parent::throwError('取消关注失败', $model->getFirstErrors());
            }
            return null;
        }
    }

    /**
     * 备注
     * @param array $params
     */
    public function remark($params = []) {
        $this->scenario = 'remark';
        if(!$this->load($params,'')){
            parent::throwError('参数非法');
        }
        if (!$this->validate()) {
            parent::throwError('提交失败', $this->getFirstErrors());
        }

        $model = UserFollower::findOrNew(['followed_user_id' => $this->followed_user_id, 'user_id' => $this->_token->user_id]);

        if ($model->isNewRecord) {
            parent::throwError('提交失败,该用户未曾关注不能备注名称');
        }

        $model->remark = $this->remark;

        if(!$model->save()){
            parent::throwError('提交失败',$model->getFirstErrors());
        }
        return $model;
    }

}
